<template>
  <div>
    <AForm :model="searchFrom" class="erp-search-form">
      <ARow class="grid-demo" :gutter="10">
        <ACol :span="6">
          <AFormItem hide-label content-class="">
            <ARangePicker v-model="searchFrom.createTime" :placeholder="['创建日期', '创建日期']" />
          </AFormItem>
        </ACol>
        <ACol :span="6">
          <AFormItem hide-label content-class="">
            <AInput v-model="searchFrom.quotationOrderCode" placeholder="报价单号" />
          </AFormItem>
        </ACol>
        <ACol :span="6">
          <AFormItem hide-label content-class="">
            <AInput v-model="searchFrom.customerName" placeholder="客户名称" />
          </AFormItem>
        </ACol>
      </ARow>
    </AForm>
    <ACard>
      <div class="erp-mb-10 w100 erp-search-btn-box">
        <ASpace>
          <AButton type="primary" @click="onSearch">
            <template #icon>
              <icon-search />
            </template>
          </AButton>
          <ATooltip content="清空筛选项" position="top">
            <AButton type="dashed" @click="onReset">
              <template #icon>
                <icon-refresh />
              </template>
            </AButton>
          </ATooltip>
          <AButton v-if="isAuth([1, 2])" type="outline" @click="openEdit('新增')">新增</AButton>
          <!-- <tableImp
            imp-url="/produce/erpCustomerImport"
            :file-temp="() => onExport('template')"
          ></tableImp> -->
          <ATooltip v-if="isAuth([1, 2])" :disabled="!shortcutBtn()" :content="shortcutBtn()">
            <AButton
              type="outline"
              staus="normal"
              :disabled="!!shortcutBtn()"
              @click="fastGenerate('salesBill')"
            >
              生成订单
            </AButton>
          </ATooltip>
          <ATooltip v-if="isAuth([1, 2])" :disabled="!isEmpty(selectRows)" content="请选择产品">
            <AButton status="danger" :disabled="isEmpty(selectRows)" @click="batchDel()">
              批量删除
            </AButton>
          </ATooltip>
        </ASpace>
        <ASpace>
          <AButton type="primary" @click="onExport('table')">导出</AButton>
        </ASpace>
      </div>
      <ATable
        ref="tableRef"
        :pagination="false"
        :data="tableData"
        :bordered="{ cell: true }"
        :span-method="spanMethod"
        column-resizable
        size="small"
        span-all
        :row-selection="{ type: 'checkbox', showCheckedAll: true }"
        row-key="quotationOrderDetailId"
        @select="
          (rowKeys: (string | number)[], rowKey: string | number, record: TableData) =>
            tableEvent('select', { rowKeys, rowKey, record })
        "
        @select-all="(checked: boolean) => tableEvent('select-all', checked)"
      >
        <template #columns>
          <ATableColumn title="报价单号" data-index="quotationOrderCode" :width="160">
          </ATableColumn>
          <ATableColumn title="客户名称" data-index="customerName" :width="160"> </ATableColumn>
          <ATableColumn title="产品名称" data-index="productName" :width="150"> </ATableColumn>
          <ATableColumn title="规格型号" data-index="specModel" :width="100" align="center">
          </ATableColumn>
          <ATableColumn title="单位" data-index="unit" :width="90" align="center"> </ATableColumn>
          <ATableColumn title="单价" data-index="unitPrice" :width="90" align="center">
          </ATableColumn>
          <ATableColumn title="含税" data-index="isInclTax" :width="65" align="center">
            <template #cell="{ record }">
              <icon-check-circle-fill v-if="record.isInclTax" style="color: #67c23a" size="20px" />
              <icon-close-circle-fill v-if="!record.isInclTax" style="color: red" size="20px" />
            </template>
          </ATableColumn>
          <ATableColumn title="送货方式" data-index="deliveryMethod" :width="90" align="center">
          </ATableColumn>
          <ATableColumn title="结算方式" data-index="paymentMethod" :width="90" align="center">
          </ATableColumn>
          <ATableColumn title="备注" data-index="remark" :width="200"> </ATableColumn>
          <ATableColumn title="创建人" data-index="createdBy" :width="120" align="center">
          </ATableColumn>
          <ATableColumn title="创建时间" data-index="createdDt" :width="120" align="center">
            <template #cell="{ record }">
              <div>{{ dayjs(record.createdDt).format('YYYY-MM-DD') }}</div>
            </template>
          </ATableColumn>
          <ATableColumn v-if="isAuth([1, 2])" title="操作" :width="145" fixed="right">
            <template #cell="{ record }">
              <ASpace>
                <AButton type="primary" size="mini" @click="rowEvent(record, 'edit')">
                  修改
                </AButton>
                <AButton type="primary" size="mini" @click="rowEvent(record, 'print')">
                  打印
                </AButton>
              </ASpace>
              <ASpace class="erp-mt-6">
                <AButton type="primary" size="mini" @click="rowEvent(record, 'copy')">
                  复制
                </AButton>
                <AButton status="danger" size="mini" @click="rowEvent(record, 'del')">
                  删除
                </AButton>
              </ASpace>
            </template>
          </ATableColumn>
        </template>
      </ATable>
      <div class="arco-table-pagination">
        <APagination
          :total="pageParam.totalCount"
          :page-size="pageParam.pageSize"
          show-total
          @change="(page: number) => tableEvent('page-change', page)"
        />
      </div>
    </ACard>
    <EditPopupForm
      v-model:visible="editModal"
      :title="editModalTitle"
      :check-data="rowData"
      @reload="
        () => {
          getTableData()
          clearTableSelect()
        }
      "
    ></EditPopupForm>
    <quotationPrint ref="quotationPrintRef" :check-data="detailData"></quotationPrint>
    <addSale
      v-model:visible="fastGenerateModal.salesBill"
      title="新增销售订单"
      :check-data="saleRes"
      from-module="quotation"
      @reload="
        () => {
          getTableData()
          clearTableSelect()
        }
      "
    ></addSale>
  </div>
</template>

<script lang="ts" setup>
import EditPopupForm from './editPopupForm.vue'
import quotationPrint from './print.vue'
import dayjs from 'dayjs'
import { Message, Modal, TableData } from '@arco-design/web-vue'
import { isAuth } from '@renderer/utils/auth'
import {
  batchDelQuotation,
  delQuotation,
  getQuotationAllList,
  getQuotationDetail,
  getQuotationPageList,
  QuotationResItem,
  QuotationSearch,
  SaleReq
} from '@renderer/api/salesDep'
// import tableImp from '@renderer/components/table/import.vue'
import addSale from '@renderer/views/salesDepartment/salesBill/editPopupForm.vue'
import { isEmpty } from 'lodash-es'

const searchFrom = ref<QuotationSearch>({
  createTime: []
})
const editModal = ref(false)
const editModalTitle = ref('新增')
const tableData = ref<QuotationResItem[]>([])
const pageParam = reactive({
  currentPage: 1,
  pageSize: 20,
  totalCount: 0
})
const quotationPrintRef = ref<InstanceType<typeof quotationPrint>>() // 打印组件
const fastGenerateModal = ref({
  salesBill: false
})
const detailData = ref<QuotationResItem>({
  quotationOrderId: '',
  quotationOrderCode: '',
  customerId: '',
  isInclTax: 0,
  deliveryMethod: '',
  paymentMethod: '',
  remark: '',
  customerName: '',
  customerAddress: '',
  contactName: '',
  contactPhone: '',
  detailList: [],
  createdBy: '',
  createdDt: '',
  updatedBy: '',
  updatedDt: '',
  quotationOrderDetailId: ''
})
const saleRes = ref<Partial<SaleReq>>({})
const selectRows = ref<any[]>([])
const tableRef = ref()

onMounted(() => {
  getTableData()
})

function clearTableSelect() {
  tableRef.value?.selectAll(false)
  selectRows.value = []
}

function formatData(baseData: QuotationResItem[]) {
  return baseData
    .map((item, index) => {
      item.index = index + 1
      if (!isEmpty(item.detailList)) {
        return item.detailList.map((detailItem, index) => {
          if (index === 0) {
            return { ...detailItem, ...item, span: item.detailList.length }
          } else {
            return { ...detailItem, ...item }
          }
        })
      } else {
        return [item]
      }
    })
    .flat()
}
async function getTableData() {
  const [createdStartDate, createdEndDate] = searchFrom.value.createTime! || []
  searchFrom.value.createdStartDate = createdStartDate
    ? dayjs(createdStartDate).format('YYYY-MM-DD')
    : ''
  searchFrom.value.createdEndDate = createdEndDate ? dayjs(createdEndDate).format('YYYY-MM-DD') : ''
  const res = await getQuotationPageList({ ...searchFrom.value, ...pageParam })
  tableData.value = formatData(res.data.list)
  pageParam.totalCount = res.data.totalCount!
}

const onSearch = () => {
  pageParam.currentPage = 1
  getTableData()
}
function onReset() {
  searchFrom.value = {
    createTime: []
  }
  pageParam.currentPage = 1
  pageParam.pageSize = 20
  getTableData()
  clearTableSelect()
}

function tableEvent(type: 'page-change' | 'select' | 'select-all', param: any) {
  switch (type) {
    case 'page-change':
      pageParam.currentPage = param
      getTableData()
      break
    case 'select':
      {
        const { rowKeys, rowKey, record } = param
        if (rowKeys.includes(rowKey)) {
          const temp = record.detailList.map((item) => {
            item.customerId = record.customerId
            return item
          })
          selectRows.value = selectRows.value?.concat(temp)
          // 判断是否全选
          const tempIDs = selectRows.value.map((item) => item.quotationOrderId)
          if (tableData.value.every((item) => tempIDs.includes(item.quotationOrderId))) {
            tableRef.value.selectAll(true)
          }
        } else {
          selectRows.value = selectRows.value?.filter(
            (item) => item.quotationOrderId != record.quotationOrderId
          )
        }
      }
      break
    case 'select-all':
      if (param) {
        selectRows.value = selectRows.value.concat(tableData.value)
      } else {
        const ids = tableData.value.map((item) => item.quotationOrderDetailId)
        selectRows.value = selectRows.value.filter(
          (item) => !ids.includes(item.quotationOrderDetailId)
        )
      }
      break

    default:
      break
  }
}

const spanMethod = ({ record, columnIndex }) => {
  if (columnIndex < 3 || columnIndex > 6) {
    if (record.span) {
      return {
        colspan: 1,
        rowspan: record.span
      }
    }
  }
}

function openEdit(title: string) {
  rowData.value = {}
  editModalTitle.value = title
  editModal.value = true
}

const rowData = ref({})
function rowEvent(row: QuotationResItem, type: 'del' | 'copy' | 'edit' | 'print') {
  switch (type) {
    case 'del':
      Modal.warning({
        title: '警告',
        content: '当前数据删除后不可恢复，是否继续？',
        okText: '确认',
        cancelText: '取消',
        simple: false,
        hideCancel: false,
        maskClosable: false,
        closable: false,
        onOk: () => {
          delQuotation({ quotationOrderId: row.quotationOrderId! }).then(() => {
            Message.success('删除成功')
            getTableData()
          })
        },
        onCancel: () => {}
      })
      break
    case 'copy':
      rowData.value = row
      editModalTitle.value = '复制'
      editModal.value = true
      break
    case 'edit':
      rowData.value = row
      editModalTitle.value = '修改'
      editModal.value = true
      break
    case 'print':
      getQuotationDetail({ quotationOrderId: row.quotationOrderId }).then((res) => {
        detailData.value = res.data
        nextTick(() => {
          quotationPrintRef.value?.printInfo()
        })
      })
      break

    default:
      break
  }
}

async function onExport(type: 'table' | 'template') {
  let fileTitle: string
  const headerData = [
    { title: '报价单号', value: 'quotationOrderCode', width: 180 },
    { title: '客户名称', value: 'customerName' },
    { title: '产品名称', value: 'productName' },
    { title: '规格型号', value: 'specModel' },
    { title: '单位', value: 'unit' },
    { title: '单价', value: 'unitPrice' },
    { title: '含税', value: 'isInclTax' },
    { title: '送货方式', value: 'deliveryMethod' },
    { title: '结算方式', value: 'paymentMethod' },
    { title: '备注', value: 'remark' }
  ]
  let excelData: any[] = []
  switch (type) {
    case 'table':
      {
        fileTitle = '报价单数据'
        headerData.unshift({ title: '序号', value: 'index', width: 80 })
        const res = await getQuotationAllList(searchFrom.value)
        excelData = formatData(res.data.list)
        excelData = excelData.map((item) => {
          item.isInclTax = item.isInclTax == 1 ? '是' : '否'
          return item
        })
      }
      break
    case 'template':
      fileTitle = '报价单导入模板'
      excelData = [
        {
          quotationOrderCode: '1883026226361159682',
          customerName: 'XXXX有限公司',
          productName: '夹心巧克力',
          specModel: '104+342+104',
          spec: '包送',
          materialCategory: '现结',
          materialCode: '测试',
          unitPrice: '10',
          isInclTax: '是',
          deliveryMethod: '包送',
          paymentMethod: '现结',
          remark: ''
        }
      ]
      break
    default:
      break
  }
  import('@renderer/utils/vendor').then((excel) => {
    excel.exportExcel(excelData, headerData, fileTitle)
  })
}

function fastGenerate(type: 'salesBill') {
  fastGenerateModal.value[type] = true
  saleRes.value = {
    customerId: selectRows.value[0].customerId,
    isInclTax: selectRows.value[0].isInclTax,
    deliveryMethod: selectRows.value[0].deliveryMethod,
    settlementType: selectRows.value[0].paymentMethod
  }
  saleRes.value.detailList = selectRows.value.map((item) => {
    return {
      productId: `${item.productId}-${item.specModel}`,
      unitPrice: item.unitPrice,
      specModel: item.specModel,
      unit: item.unit,
      qty: 0,
      amt: 0
    }
  })
}

function shortcutBtn() {
  if (isEmpty(selectRows.value)) {
    return '请选择产品'
  }
  const temp: string[] = []
  for (const item of selectRows.value) {
    if (!temp.includes(item.customerId)) {
      temp.push(item.customerId)
    }
  }
  if (temp.length > 1) {
    return '请选择相同客户的报价单'
  }
  return ''
}

function batchDel() {
  const idList = selectRows.value.map((item) => item.quotationOrderId)
  batchDelQuotation({ idList: idList }).then(() => {
    Message.success('删除成功')
    onSearch()
    clearTableSelect()
  })
}
</script>
<style lang="less" scoped>
.erp-search-btn-box {
  display: flex;
  justify-content: space-between;
  align-items: center;
}
</style>
